﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;

namespace HJT212_Protocol_Server.DAO
{
    public class MsgCacheDao
    {
        private static string connStr = ConfigurationManager.AppSettings["connStr"];
        /// <summary>
        /// 将第一次发送的请求写入缓存，初次请求由HostClient发起，
        /// 生成QN，此时会把QN与SrvClient的ID的对应缓存起来，
        /// 当本次请求，有回执的时候，以便可知回执给哪个SrvClient
        /// 判断是否是初次请求的操作是根据是根据指令的起始，
        /// 如果以'QN='打头说明是初次请求，
        /// 如果以'ST='打头说明是请求的应答
        /// </summary>
        /// <param name="msgContent">内容</param>
        /// <param name="MN"> </param>
        public void InsertToCache(string msgContent, string MN)
        {
            try
            {
                if (string.IsNullOrEmpty(msgContent.Trim()) || string.IsNullOrEmpty(MN))
                {
                    return;
                }
                string qnd = "QN=";
                //为了较好的兼容性，即便是QN与=间有空格也可取出相应的QN号
                string content = msgContent.ToUpper().Replace(" ", "").Replace("　", "");
                int i = content.IndexOf(qnd);
                if (i != 0) return;
                //大于0说明是非初次请求，小于0说明是指令信息中无请求码
                string qn = content.Substring(i + 3, 17);
                string insrtSql =
                    @" insert into TB_MESSAGECACHELIST (MN, QN) values ('{0}', '{1}') ";
                insrtSql = string.Format(insrtSql, MN, qn);
                FirebirdHelper helper = new FirebirdHelper(connStr);
                helper.ExecuteNonQuery(insrtSql);
                //return qn;
            }
            catch (Exception ex)
            {

                throw;
            }
        }


        /// <summary>
        /// 从缓存中根据QN检索相应的MN，从而定位到相应的上位机
        /// </summary>
        /// <returns></returns>
        public string FindMNByQNFromCache(string QN)
        {
            try
            {
                if (string.IsNullOrEmpty(QN))
                {
                    return null;
                }
                string sqlSelect = " select First 1 MN, QN from TB_MESSAGECACHELIST where  QN='{0}' ";
                sqlSelect = string.Format(sqlSelect, QN);
                FirebirdHelper helper = new FirebirdHelper(connStr);
                DataTable dt = helper.Data_Table(sqlSelect);
                if (dt != null && dt.Rows.Count > 0)
                {
                    string MN = string.Format("{0}", dt.Rows[0]["MN"]);
                    return MN;
                }
            }
            catch (Exception ex)
            {

                throw;
            }
            return null;
        }


    }
}
